﻿using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
using YunHao;

namespace UnknowWorld.CardGame
{

    public class EnemyPool : MonoBehaviour
    {
        public static EnemyPool Instance
        {
            get
            {
                if (!instance)
                    instance = new GameObject("EnemyPool", typeof(EnemyPool)).GetComponent<EnemyPool>();
                return instance;
            }
        }

        private static EnemyPool instance;

        void Awake()
        {
            if (!instance)
                instance = this;
        }

        private void OnEnable()
        {
            InitEnemeyPool();
        }

        private void OnDisable()
        {
            _dataPool.Clear();
            DestroyPicturePool();
            _dataLoaded = false;
        }

        #region Load Data

        /// <summary>
        /// 所有敌人数据
        /// </summary>
        public List<Enemey> Enemeys
        {
            get
            {
                return _dataPool;
            }
        } 

        /// <summary>
        /// 是否加载成功
        /// </summary>
        public bool Loaded
        {
            get
            {
                return _dataLoaded;
            }
        }

        /// <summary>
        /// 敌人池
        /// </summary>
        private List<Enemey> _dataPool = new List<Enemey>();

        /// <summary>
        /// 敌人图片路径
        /// </summary>
        private string _enemyPictureDir;

        /// <summary>
        /// 数据加载是否完成
        /// </summary>
        private bool _dataLoaded;

        /// <summary>
        /// 初始化本地敌人数据
        /// </summary>
        void InitEnemeyPool()
        {
            string enemeyDir = Path.Combine(Application.streamingAssetsPath, "Enemy");
            string enemeyDirPath = Path.Combine(enemeyDir, "Enemys.dat");
            _enemyPictureDir = Path.Combine(enemeyDir, "Images");
            LoadEnemeyPool(enemeyDirPath);
        }

        /// <summary>
        /// 加载本地敌人数据
        /// </summary>
        /// <param name="path">敌人数据文件路径</param>
        void LoadEnemeyPool(string path)
        {
            XmlControl.ReadXmlAsync<List<Enemey>>(path, (enemeys) =>
            {
                _dataPool = enemeys;
                _dataLoaded = true;
            }, (err) =>
            {
                Debug.LogErrorFormat("Enemey Load Fail:", err);
            });
        }
        /// <summary>
        /// 通过key获取Enemey
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public Enemey EnemeyByKey(string key)
        {
            Enemey enemey = null;
            foreach (var ey in _dataPool)
            {
                if (ey.Key == key)
                {
                    enemey = ey.Clone();
                    break;
                }
            }
            return enemey;
        }

        #endregion

        #region Picture Pool

        /// <summary>
        /// 卡牌图片池
        /// </summary>
        private Dictionary<string, Texture2D> _enemyPicturePool = new Dictionary<string, Texture2D>();

        /// <summary>
        /// 销毁图片池
        /// </summary>
        void DestroyPicturePool()
        {
            foreach (var kv in _enemyPicturePool)
            {
                var texture = kv.Value;
                if (texture) Destroy(texture);
            }
            _enemyPicturePool.Clear();
        }

        /// <summary>
        /// 获取卡牌图片Sprite
        /// </summary>
        /// <param name="enemey"></param>
        /// <returns></returns>
        public void LoadEnemyPictureSprite(Enemey enemey, System.Action<Sprite> onFinish)
        {
            System.Action<Texture2D> onSuccess = (tex) =>
            {
                var sprite = Sprite.Create(tex, new Rect(0, 0, tex.width, tex.height), new Vector2(.5f, .5f));
                onFinish(sprite);
            };

            if (_enemyPicturePool.ContainsKey(enemey.PicAddress))
            {
                onSuccess(_enemyPicturePool[enemey.PicAddress]);
                return;
            }
            string url = Path.Combine(_enemyPictureDir, enemey.PicAddress);
            ResourceLoadControl.Instance.LoadTexture2D(url, (tex) =>
            {
                if (tex)
                {
                    if (_enemyPicturePool.ContainsKey(enemey.PicAddress))
                    {
                        onSuccess(_enemyPicturePool[enemey.PicAddress]);
                        Destroy(tex);
                    }
                    else
                    {
                        _enemyPicturePool.Add(enemey.PicAddress, tex);
                        onSuccess(tex);
                    }
                }
                else
                {
                    Debug.LogWarning("无法获取地方图片");
                }
            }, (err) =>
            {
                Debug.LogWarningFormat("获取地方图片失败:{0}", err);
            });
        }

        #endregion
    }
}